package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.swing.*;
import java.util.List;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {
    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private ClazzService clazzService;

    //条件分页查询学生（使用MYbatis-plus）
    @Override
    public PageResult<Student> getPageResult(StudentQueryParam param) {
        Page<Student> page = Page.of(param.getPage(), param.getPageSize());
        // 根据最后修改时间倒序排序
        page.addOrder(OrderItem.desc("update_time"));

        // 使用LambdaQuery来构建查询学员（student）条件，并返回分页结果(通过name学员姓名，degree学历(1:初中,2:高中,3:大专,4:本科,5:硕士,6:博士)，clazzid班级id查询)
        page = lambdaQuery().like(param.getName() != null && !param.getName().isEmpty(), Student::getName, param.getName())
                .eq(param.getDegree() != null, Student::getDegree, param.getDegree())
                .eq(param.getClazzId() != null, Student::getClazzId, param.getClazzId())
                .page(page);

        // 添加班级名称（student表中的clazz_id与clazz表中的id相等）
        List<Student> students = page.getRecords();
        students.forEach(student -> {
            Clazz clazz = clazzService.getById(student.getClazzId());
            if (clazz != null) {
                student.setClazzName(clazz.getName());
            }
        });

        return new PageResult<>(page.getTotal(), students);
    }

    @Override
    public boolean addStudent(Student student) {
        // 校验必填字段
        if (student.getId() == null ||
                student.getName() == null || student.getName().isEmpty() ||
                student.getNo() == null || student.getNo().isEmpty() ||
                student.getPhone() == null || student.getPhone().isEmpty() ||
                student.getGender() == null ||
                student.getDegree() == null) {
            return false;
        }

        // 保存学生信息
        return save(student);
    }


}
